<template>
  <div class="profile-container">
    <!-- 顶部导航 -->
    <div class="header">
      <el-button @click="goBack" icon="ArrowLeft">返回首页</el-button>
      <h2>个人中心</h2>
    </div>

    <!-- 个人信息 -->
    <el-card class="user-card">
      <div class="user-profile">
        <el-avatar :src="userInfo.avatar" :size="80" />
        <div class="user-details">
          <h3>{{ userInfo.nickName }}</h3>
          <p>账号：{{ userInfo.accountNumber }}</p>
        </div>
      </div>
    </el-card>

    <!-- 标签切换 -->
    <el-tabs v-model="activeTab" class="profile-tabs">
      <!-- 我发布的商品 -->
      <el-tab-pane label="我发布的" name="published">
        <div v-loading="loading">
          <el-empty v-if="publishedList.length === 0" description="暂无发布" />
          <el-row :gutter="20" v-else>
            <el-col :span="6" v-for="item in publishedList" :key="item.id">
              <el-card class="goods-card" shadow="hover">
                <div class="goods-image">
                  <img :src="getFirstImage(item.pictureList)" alt="商品图片" />
                </div>
                <div class="goods-info">
                  <h4>{{ item.idleName }}</h4>
                  <p class="price">¥{{ item.idlePrice }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 我购买的订单 -->
      <el-tab-pane label="我购买的" name="purchased">
        <div v-loading="loading">
          <el-empty v-if="orderList.length === 0" description="暂无订单" />
          <el-table :data="orderList" v-else>
            <el-table-column prop="orderNumber" label="订单号" width="200" />
            <el-table-column label="商品名称">
              <template #default="scope">
                {{ scope.row.idleItem?.idleName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="价格">
              <template #default="scope">
                ¥{{ scope.row.orderPrice }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from '../api'

const router = useRouter()
const userInfo = ref({})
const activeTab = ref('published')
const loading = ref(false)
const publishedList = ref([])
const orderList = ref([])

onMounted(() => {
  const storedUserInfo = sessionStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
    loadPublishedItems()
  }
})

// 监听标签切换
watch(activeTab, (newTab) => {
  if (newTab === 'published') {
    loadPublishedItems()
  } else {
    loadOrders()
  }
})

// 返回首页
const goBack = () => {
  router.push('/index')
}

// 加载我发布的商品
const loadPublishedItems = async () => {
  loading.value = true
  try {
    const res = await api.getMyPublishedItems()
    if (res.status_code === 1) {
      publishedList.value = res.data || []
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 加载我的订单
const loadOrders = async () => {
  loading.value = true
  try {
    const res = await api.getMyOrders()
    if (res.status_code === 1) {
      orderList.value = res.data || []
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 获取第一张图片
const getFirstImage = (pictureList) => {
  if (!pictureList) return '/default-image.jpg'
  const images = pictureList.split(',')
  return images[0] || '/default-image.jpg'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.user-card {
  margin-bottom: 20px;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-details h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.user-details p {
  margin: 0;
  color: #909399;
}

.profile-tabs {
  background: white;
  padding: 20px;
  border-radius: 4px;
}

.goods-card {
  margin-bottom: 20px;
}

.goods-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
  background-color: #f5f5f5;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  padding: 12px 0;
}

.goods-info h4 {
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}
</style>
